import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Layout, Input, Button, List, Avatar, Typography, Card, Spin, Tag, Dropdown, Space, Modal, Form, Upload, Divider, Alert, message, Badge } from 'antd';
import {
  SendOutlined,
  UserOutlined,
  PaperClipOutlined,
  FileOutlined,
  PlusOutlined,
  MoreOutlined,
  ExclamationCircleOutlined,
  MessageOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import { useAuth } from '../context/AuthContext';
import chatService from '../services/chatService';
import socketService from '../services/socket';
import moment from 'moment';
import '../styles/ChatPage.css';
import crmService from '../services/crmService';
import api from '../services/api';
import _ from 'lodash'; // 导入lodash进行节流和防抖

const { Sider, Content } = Layout;
const { TextArea } = Input;
const { Title, Text, Paragraph } = Typography;

const ChatPage = () => {
  const { contactId } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const messagesEndRef = useRef(null);
  
  const [contacts, setContacts] = useState([]);
  const [messages, setMessages] = useState([]);
  const [activeContact, setActiveContact] = useState(null);
  const [messageInput, setMessageInput] = useState('');
  const [loading, setLoading] = useState(true);
  const [loadingMessages, setLoadingMessages] = useState(true);
  const [presetFiles, setPresetFiles] = useState([]);
  const [presetMenuVisible, setPresetMenuVisible] = useState(false);
  const [isAdmin] = useState(user?.role === 'admin');
  const [uploadLoading, setUploadLoading] = useState(false);
  const [loadingMoreMessages, setLoadingMoreMessages] = useState(false);
  const [hasMoreMessages, setHasMoreMessages] = useState(true);
  const [oldestMessageId, setOldestMessageId] = useState(null);
  const [typing, setTyping] = useState(false);
  const [activeTime, setActiveTime] = useState(0);
  const [lastActivity, setLastActivity] = useState(null);
  const [timerActive, setTimerActive] = useState(false);
  const activityTimerRef = useRef(null);
  const [searchInput, setSearchInput] = useState('');

  // 使用节流函数优化活动上报 - 移动到前面
  const reportActivity = useCallback(
    _.throttle((seconds, sessionId) => {
      if (!sessionId) return;
      
      api.post('/activity/active-time', {
        seconds,
        sessionId
      }).catch(err => {
        console.error('活跃时间上报失败:', err);
      });
    }, 10000), // 10秒内最多触发一次
    []
  );

  // 加载数据
  useEffect(() => {
    // 连接WebSocket
    if (user) {
      socketService.connectSocket(localStorage.getItem('token'));
    }
    
    // 加载联系人列表
    const fetchContacts = async () => {
      try {
        setLoading(true);
        const fetchedContacts = await chatService.getChats();
        setContacts(fetchedContacts);
        
        // 设置当前选中的联系人
        if (contactId) {
          const current = fetchedContacts.find(c => c.id === contactId);
          if (current) {
            setActiveContact(current);
            loadMessages(contactId);
          } else if (fetchedContacts.length > 0) {
            setActiveContact(fetchedContacts[0]);
            navigate(`/chat/${fetchedContacts[0].id}`);
          }
        } else if (fetchedContacts.length > 0) {
          setActiveContact(fetchedContacts[0]);
          navigate(`/chat/${fetchedContacts[0].id}`);
        }
      } catch (error) {
        console.error('获取联系人失败:', error);
        message.error('获取联系人列表失败，请重试');
      } finally {
        setLoading(false);
      }
    };
    
    // 加载预设文件
    const fetchPresetFiles = async () => {
      try {
        // 在实际项目中，这里应该从API获取预设文件
        // const response = await api.get('/preset-files');
        // setPresetFiles(response.data);
        
        // 模拟预设文件数据
        setPresetFiles([
          { id: 1, name: '产品目录', type: 'pdf' },
          { id: 2, name: '价格表', type: 'excel' },
          { id: 3, name: '公司介绍', type: 'ppt' }
        ]);
      } catch (error) {
        console.error('获取预设文件失败:', error);
        message.error('获取预设文件失败，请重试');
      }
    };
    
    fetchContacts();
    fetchPresetFiles();
    
    // 监听新消息
    socketService.onEvent('message:received', (newMessage) => {
      console.log('收到新消息:', newMessage);
      
      // 处理收到的新消息
      if (newMessage.from && newMessage.from.id) {
        const fromContactId = newMessage.from.id;
        
        // 检测敏感内容
        const hasSensitiveContent = newMessage.hasSensitiveContent || isSensitiveContent({
          type: newMessage.type || 'text',
          content: newMessage.body
        });
        
        if (hasSensitiveContent && isAdmin) {
          // 为管理员播放提示音
          const audio = new Audio('/alert.mp3');
          audio.play().catch(err => console.log('播放提示音失败:', err));
        }
        
        // 更新联系人列表中的最后消息
        setContacts(prevContacts => {
          return prevContacts.map(contact => {
            if (contact.id === fromContactId) {
              return {
                ...contact,
                lastMessage: newMessage.body,
                lastMessageTime: newMessage.timestamp,
                unreadCount: (contact.unreadCount || 0) + 1,
                hasSensitive: hasSensitiveContent || contact.hasSensitive
              };
            }
            return contact;
          });
        });
        
        // 如果是当前选中的联系人，则添加到消息列表并标记为已读
        if (activeContact && fromContactId === activeContact.id) {
          const formattedMessage = {
            id: newMessage.id,
            content: newMessage.body,
            timestamp: newMessage.timestamp,
            direction: 'inbound',
            fromMe: false,
            sender: { 
              id: fromContactId, 
              name: newMessage.from.name || activeContact.name || '联系人'
            },
            type: newMessage.type || 'text',
            hasSensitive: hasSensitiveContent,
          };
          
          console.log('格式化后的新消息:', formattedMessage);
          
          setMessages(prev => [...prev, formattedMessage]);
          
          // 标记为已读
          chatService.markChatAsRead(fromContactId).catch(error => {
            console.error('标记为已读失败:', error);
          });
          
          // 滚动到底部
          scrollToBottom();
        }
      }
    });
    
    // 监听WhatsApp状态变化
    socketService.onEvent('whatsapp:status', (status) => {
      console.log('WhatsApp状态变化:', status);
      // 可以处理状态变化，例如显示连接状态
    });
    
    return () => {
      // 清理WebSocket事件监听
      socketService.offEvent('message:received');
      socketService.offEvent('whatsapp:status');
    };
  }, [contactId, navigate, user]);

  // 模拟对方正在输入
  useEffect(() => {
    if (activeContact) {
      let timer;
      // 当收到新消息后，随机触发"正在输入"状态
      if (messages.length > 0 && messages[messages.length - 1].direction === 'outbound') {
        const randomDelay = Math.floor(Math.random() * 3000) + 1000; // 1-4秒随机延迟
        timer = setTimeout(() => {
          setTyping(true);
          // 显示1-3秒后消失
          setTimeout(() => setTyping(false), Math.floor(Math.random() * 2000) + 1000);
        }, randomDelay);
      }
      
      return () => {
        clearTimeout(timer);
        setTyping(false);
      };
    }
  }, [messages, activeContact]);

  // 修改活跃度追踪功能，添加上报到服务器的代码
  useEffect(() => {
    if (!isAdmin) { // 只对销售人员追踪活跃度
      const REPORT_INTERVAL = 60; // 改为60秒上报一次
      const IDLE_TIMEOUT = 60; // 60秒无操作视为空闲
      
      const handleActivity = () => {
        const now = Date.now();
        if (!lastActivity || (now - lastActivity) > IDLE_TIMEOUT * 1000) { // 如果空闲超过预设时间，重新开始计时
          setTimerActive(true);
        }
        setLastActivity(now);
      };

      // 活跃度计时器
      const activityTimer = setInterval(() => {
        if (timerActive && lastActivity && (Date.now() - lastActivity) < IDLE_TIMEOUT * 1000) {
          setActiveTime(prev => prev + 1);
          
          // 每REPORT_INTERVAL秒向服务器上报一次活跃时间
          if (activeTime > 0 && activeTime % REPORT_INTERVAL === 0) {
            const sessionId = localStorage.getItem('sessionId') || null;
            if (sessionId) {
              // 使用节流优化过的函数上报活跃时间
              reportActivity(REPORT_INTERVAL, sessionId);
            }
          }
        } else if (timerActive && lastActivity && (Date.now() - lastActivity) >= IDLE_TIMEOUT * 1000) {
          setTimerActive(false);
          
          // 如果空闲超过预设时间，上报剩余的活跃时间
          const remainingSeconds = activeTime % REPORT_INTERVAL;
          if (remainingSeconds > 0) {
            const sessionId = localStorage.getItem('sessionId') || null;
            if (sessionId) {
              reportActivity(remainingSeconds, sessionId);
            }
          }
        }
      }, 1000);

      // 监听各种用户活动
      const events = ['keydown', 'mousedown', 'mousemove', 'scroll', 'touchstart', 'click'];
      events.forEach(event => {
        window.addEventListener(event, handleActivity, { passive: true });
      });
      
      // 监听页面失焦事件
      const handleVisibilityChange = () => {
        if (document.hidden) {
          // 页面失焦时上报累积的活跃时间
          const sessionId = localStorage.getItem('sessionId');
          const remainingSeconds = activeTime % REPORT_INTERVAL;
          
          if (sessionId && remainingSeconds > 0) {
            reportActivity(remainingSeconds, sessionId);
          }
          
          setTimerActive(false);
        } else {
          // 页面重新获得焦点时重新开始计时
          handleActivity();
        }
      };
      
      document.addEventListener('visibilitychange', handleVisibilityChange);

      // 在组件卸载时清理所有事件监听和上报剩余活跃时间
      return () => {
        events.forEach(event => {
          window.removeEventListener(event, handleActivity);
        });
        document.removeEventListener('visibilitychange', handleVisibilityChange);
        clearInterval(activityTimer);
        
        // 上报剩余的活跃时间
        const remainingSeconds = activeTime % REPORT_INTERVAL;
        const sessionId = localStorage.getItem('sessionId');
        
        if (sessionId && remainingSeconds > 0) {
          reportActivity(remainingSeconds, sessionId);
        }
      };
    }
  }, [isAdmin, lastActivity, timerActive, activeTime, reportActivity]);

  // 加载特定联系人的消息
  const loadMessages = async (id) => {
    if (!id) {
      console.warn('无法加载消息：未提供联系人ID');
      return;
    }
    
    try {
      setLoadingMessages(true);
      
      // 先尝试标记为已读，作为非阻塞操作
      // 使用Promise.resolve跳出主流程，使其在后台执行而不阻塞消息加载
      Promise.resolve().then(async () => {
        try {
          console.log(`开始标记聊天为已读（非阻塞）: ${id}`);
          
          // 添加重试机制
          let retryCount = 0;
          const maxRetries = 2;
          let result = null;
          
          while (retryCount <= maxRetries) {
            try {
              // 每次重试时稍微延迟增加
              if (retryCount > 0) {
                await new Promise(resolve => setTimeout(resolve, retryCount * 1000));
                console.log(`尝试第 ${retryCount} 次重试标记已读...`);
              }
              
              result = await chatService.markChatAsRead(id);
              
              // 如果成功或者是静默错误，中断重试
              if (result && (result.success || result.silentError)) {
                break;
              }
              
              retryCount++;
            } catch (innerError) {
              console.log(`标记为已读第 ${retryCount} 次尝试失败:`, innerError);
              retryCount++;
              
              // 最后一次重试也失败，就放弃
              if (retryCount > maxRetries) {
                console.warn('已达到最大重试次数，放弃标记为已读');
                break;
              }
            }
          }
          
          console.log('标记聊天为已读结果:', result);
          
          // 标记成功后，更新联系人列表中的未读数
          if (result && result.success) {
            setContacts(prevContacts => prevContacts.map(contact => 
              contact.id === id ? { ...contact, unreadCount: 0 } : contact
            ));
          }
        } catch (readError) {
          // 完全忽略错误，这是非关键操作
          console.log('标记为已读操作忽略错误:', readError);
        }
      });
      
      // 获取聊天消息
      const chatMessages = await chatService.getChatHistory(id);
      
      // 记录获取到的消息
      console.log(`获取到${chatMessages.length}条原始消息，类型:`, 
                 Array.isArray(chatMessages) ? 'Array' : typeof chatMessages);
      
      if (chatMessages.length > 0) {
        // 检查第一条消息的结构
        console.log('第一条消息样本:', JSON.stringify(chatMessages[0], null, 2));
      } else {
        console.log('没有获取到任何消息');
      }
      
      // 转换消息格式，添加强化的安全检查以避免undefined错误
      const formattedMessages = chatMessages.map((msg, index) => {
        // 添加安全检查
        if (!msg) {
          console.log(`消息 #${index} 为空，跳过`);
          return null;
        }
        
        // 检查消息结构
        const msgType = typeof msg;
        if (msgType !== 'object') {
          console.log(`消息 #${index} 类型不是对象，而是 ${msgType}`);
          // 如果是字符串，尝试解析
          if (msgType === 'string') {
            try {
              const parsed = JSON.parse(msg);
              if (parsed && typeof parsed === 'object') {
                console.log(`成功解析消息 #${index} 为对象`);
                msg = parsed;
              }
            } catch (e) {
              console.log(`消息 #${index} 不是有效的JSON字符串`);
            }
          }
        }
        
        // 确保必要字段存在并提供默认值
        // 判断消息方向：fromMe为true时是自己发送的(outbound)，否则是接收的(inbound)
        const isFromMe = msg.fromMe === true || 
                          (msg.from?.id === 'me') || 
                          (msg.sender?.id === 'me');
                          
        console.log(`消息 #${index} fromMe=${isFromMe}`, msg.from, msg.fromMe);
        
        // 获取发送者ID
        const fromId = msg.from?.id || (isFromMe ? 'me' : id);
        
        // 获取消息内容 - 优先尝试body, text, 或message字段
        let messageContent = '内容不可用';
        if (msg.body !== undefined) {
          messageContent = msg.body;
        } else if (msg.text !== undefined) {
          messageContent = msg.text;
        } else if (msg.content !== undefined) {
          messageContent = msg.content;
        } else if (msg.message !== undefined) {
          messageContent = msg.message;
        } else if (typeof msg === 'string') {
          // 如果整个消息就是字符串，直接使用
          messageContent = msg;
        }
        
        // 处理复杂类型的消息对象
        if (messageContent === '内容不可用' && typeof msg === 'object') {
          // 遍历对象寻找可能的内容字段
          for (const key in msg) {
            if (typeof msg[key] === 'string' && 
                ['body', 'text', 'content', 'message', 'caption', 'data'].includes(key)) {
              messageContent = msg[key];
              console.log(`消息 #${index} 从字段 ${key} 中找到内容`);
              break;
            }
          }
          
          // 如果仍然找不到内容，记录消息的所有键
          if (messageContent === '内容不可用') {
            console.log(`消息 #${index} 没有找到内容，可用键:`, Object.keys(msg));
          }
        }
        
        // 确保消息方向明确
        const messageDirection = isFromMe ? 'outbound' : 'inbound';
        
        // 创建格式化的消息对象
        const formattedMsg = {
          id: msg.id || `temp_${Date.now()}_${Math.random()}`,
          content: messageContent,
          timestamp: msg.timestamp || new Date().toISOString(),
          direction: messageDirection,
          sender: { 
            id: fromId, 
            name: isFromMe ? '我' : (activeContact?.name || '联系人')
          },
          type: msg.type || 'text',
          hasSensitive: msg.hasSensitiveContent || (messageDirection === 'inbound' && isSensitiveContent({
            type: msg.type || 'text',
            content: messageContent
          })),
          status: msg.status || 'sent',
          fromMe: isFromMe,
          ...(msg.originalContent && { originalContent: msg.originalContent }),
          ...(msg.media && { media: msg.media })
        };
        
        // 记录内容是否成功提取
        if (messageContent !== '内容不可用') {
          console.log(`消息 #${index} (${formattedMsg.id}) 内容提取成功，方向: ${formattedMsg.direction}, 长度: ${messageContent.length}`);
        } else {
          console.log(`消息 #${index} (${formattedMsg.id}) 内容提取失败`);
        }
        
        return formattedMsg;
      }).filter(Boolean); // 过滤掉null值
      
      console.log(`成功格式化 ${formattedMessages.length}/${chatMessages.length} 条消息`);
      setMessages(formattedMessages);
      
      // 如果有消息，记录最早的消息ID用于加载更多
      if (formattedMessages.length > 0) {
        setOldestMessageId(formattedMessages[0].id);
        setHasMoreMessages(formattedMessages.length >= 50); // 如果返回的消息数量达到限制，假设还有更多
      } else {
        setHasMoreMessages(false);
      }
      
      // 滚动到底部
      scrollToBottom();
    } catch (error) {
      console.error('获取消息历史失败:', error);
      message.error('获取聊天历史失败，请重试');
      
      // 设置一个空数组，以避免显示旧的聊天记录
      setMessages([]);
      setHasMoreMessages(false);
    } finally {
      setLoadingMessages(false);
    }
  };

  // 加载更多历史消息
  const loadMoreMessages = async () => {
    if (!activeContact || !hasMoreMessages || loadingMoreMessages) {
      return;
    }
    
    try {
      setLoadingMoreMessages(true);
      
      console.log(`开始加载更多消息，联系人: ${activeContact.id}, 最早消息ID: ${oldestMessageId}`);
      
      // 获取更早的消息
      const oldMessages = await chatService.getChatHistory(
        activeContact.id, 
        50, 
        oldestMessageId
      );
      
      console.log(`加载到${oldMessages.length}条更早的消息`);
      
      if (oldMessages.length === 0) {
        setHasMoreMessages(false);
        console.log('没有更多历史消息了');
        return;
      }
      
      // 转换消息格式，添加同样的安全检查
      const formattedOldMessages = oldMessages.map((msg, index) => {
        // 添加安全检查
        if (!msg) return null;
        
        // 判断消息方向：fromMe为true时是自己发送的(outbound)，否则是接收的(inbound)
        const isFromMe = msg.fromMe === true || 
                        (msg.from?.id === 'me') || 
                        (msg.sender?.id === 'me');
                        
        console.log(`历史消息 #${index} fromMe=${isFromMe}`, msg.from, msg.fromMe);
        
        // 获取发送者ID
        const fromId = msg.from?.id || (isFromMe ? 'me' : activeContact.id);
        
        // 获取消息内容 - 优先尝试body, text, 或message字段
        let messageContent = '内容不可用';
        if (msg.body !== undefined) {
          messageContent = msg.body;
        } else if (msg.text !== undefined) {
          messageContent = msg.text;
        } else if (msg.content !== undefined) {
          messageContent = msg.content;
        } else if (msg.message !== undefined) {
          messageContent = msg.message;
        } else if (typeof msg === 'string') {
          // 如果整个消息就是字符串，直接使用
          messageContent = msg;
        }
        
        // 处理复杂类型的消息对象
        if (messageContent === '内容不可用' && typeof msg === 'object') {
          // 遍历对象寻找可能的内容字段
          for (const key in msg) {
            if (typeof msg[key] === 'string' && 
                ['body', 'text', 'content', 'message', 'caption', 'data'].includes(key)) {
              messageContent = msg[key];
              break;
            }
          }
        }
        
        // 确保消息方向明确
        const messageDirection = isFromMe ? 'outbound' : 'inbound';
        
        return {
          id: msg.id || `temp_${Date.now()}_${Math.random()}`,
          content: messageContent,
          timestamp: msg.timestamp || new Date().toISOString(),
          direction: messageDirection,
          sender: { 
            id: fromId, 
            name: isFromMe ? '我' : (activeContact.name || '联系人')
          },
          type: msg.type || 'text',
          hasSensitive: msg.hasSensitiveContent || false,
          status: msg.status || 'sent',
          fromMe: isFromMe, // 添加明确的fromMe标记
          ...(msg.originalContent && { originalContent: msg.originalContent }),
          ...(msg.media && { media: msg.media })
        };
      }).filter(Boolean); // 过滤掉null值
      
      if (formattedOldMessages.length === 0) {
        console.log('格式化后没有有效消息，停止加载更多');
        setHasMoreMessages(false);
        return;
      }
      
      console.log(`成功格式化${formattedOldMessages.length}条历史消息`);
      
      // 查找最早的消息ID
      let newOldestId = null;
      if (formattedOldMessages.length > 0) {
        // 确保我们总是找到一个有效的消息ID
        const validOldMessages = formattedOldMessages.filter(m => m.id && m.id !== oldestMessageId);
        if (validOldMessages.length > 0) {
          newOldestId = validOldMessages[0].id;
          console.log(`新的最早消息ID: ${newOldestId}`);
        }
      }
      
      // 更新最早消息ID
      if (newOldestId) {
        setOldestMessageId(newOldestId);
        setHasMoreMessages(formattedOldMessages.length >= 20); // 如果返回足够多消息，假设还有更多
      } else {
        // 如果找不到新的最早ID，说明可能已经到了历史记录的开始
        setHasMoreMessages(false);
      }
      
      // 合并消息列表（旧消息在前，当前消息在后）
      // 检查并避免重复消息
      const existingIds = new Set(messages.map(m => m.id));
      const uniqueOldMessages = formattedOldMessages.filter(m => !existingIds.has(m.id));
      
      console.log(`添加${uniqueOldMessages.length}条唯一历史消息到列表`);
      
      setMessages(prev => [...uniqueOldMessages, ...prev]);
    } catch (error) {
      console.error('加载更多消息失败:', error);
      message.error('加载更多消息失败，请重试');
      // 重试次数过多时，停止尝试
      if (error.retryCount && error.retryCount > 3) {
        setHasMoreMessages(false);
      }
    } finally {
      setLoadingMoreMessages(false);
    }
  };

  // 发送消息
  const handleSendMessage = async () => {
    if (!messageInput.trim() || !activeContact) return;
    
    const newMessage = {
      id: Date.now().toString(),
      content: messageInput,
      timestamp: new Date().toISOString(),
      direction: 'outbound',
      fromMe: true,
      sender: { id: 'me', name: '我' },
      type: 'text',
      hasSensitive: false
    };
    
    // 先添加到本地消息列表
    setMessages(prev => [...prev, newMessage]);
    setMessageInput('');
    
    // 滚动到底部
    scrollToBottom();
    
    try {
      // 调用API发送消息
      const result = await chatService.sendMessage(activeContact.id, messageInput);
      
      // 更新消息ID（使用服务器返回的ID）
      if (result && result.messageId) {
        setMessages(prev => prev.map(msg => 
          msg.id === newMessage.id ? { ...msg, id: result.messageId } : msg
        ));
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      message.error('发送消息失败，请重试');
      
      // 可以考虑标记消息为发送失败状态
      setMessages(prev => prev.map(msg => 
        msg.id === newMessage.id ? { ...msg, failed: true } : msg
      ));
    }
  };

  // 处理预设文件发送
  const handleSendPresetFile = async (fileId) => {
    const file = presetFiles.find(f => f.id === fileId);
    if (!file || !activeContact) return;
    
    const newMessage = {
      id: Date.now().toString(),
      content: `[文件] ${file.name}.${file.type}`,
      timestamp: new Date().toISOString(),
      direction: 'outbound',
      fromMe: true,
      sender: { id: 'me', name: '我' },
      type: 'file',
      fileData: { name: file.name, type: file.type },
      hasSensitive: false
    };
    
    // 先添加到本地消息列表
    setMessages(prev => [...prev, newMessage]);
    setPresetMenuVisible(false);
    
    // 滚动到底部
    scrollToBottom();
    
    try {
      // 调用API发送预设文件
      const result = await chatService.sendPresetFile(activeContact.id, fileId);
      
      // 更新消息ID（使用服务器返回的ID）
      if (result && result.messageId) {
        setMessages(prev => prev.map(msg => 
          msg.id === newMessage.id ? { ...msg, id: result.messageId } : msg
        ));
      }
    } catch (error) {
      console.error('发送预设文件失败:', error);
      message.error('发送预设文件失败，请重试');
      
      // 可以考虑标记消息为发送失败状态
      setMessages(prev => prev.map(msg => 
        msg.id === newMessage.id ? { ...msg, failed: true } : msg
      ));
    }
  };

  // 处理文件上传
  const handleFileUpload = async (file) => {
    if (!activeContact) return;
    
    setUploadLoading(true);
    
    try {
      let result;
      if (file.type.startsWith('image/')) {
        // 上传图片
        result = await chatService.sendImage(activeContact.id, file);
      } else {
        // 上传其他文件
        result = await chatService.sendFile(activeContact.id, file);
      }
      
      // 添加到消息列表
      const newMessage = {
        id: result.messageId,
        content: file.type.startsWith('image/') 
          ? `[图片] ${file.name}` 
          : `[文件] ${file.name}`,
        timestamp: new Date().toISOString(),
        direction: 'outbound',
        sender: { id: 'me', name: '我' },
        type: file.type.startsWith('image/') ? 'image' : 'file',
        hasSensitive: false
      };
      
      setMessages(prev => [...prev, newMessage]);
      
      // 滚动到底部
      scrollToBottom();
      
      message.success('文件发送成功');
    } catch (error) {
      console.error('发送文件失败:', error);
      message.error('发送文件失败，请重试');
    } finally {
      setUploadLoading(false);
    }
    
    return false; // 阻止默认上传行为
  };

  // 滚动到底部
  const scrollToBottom = () => {
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, 100);
  };

  // 处理消息内容显示
  const renderMessageContent = (message) => {
    // 处理系统消息
    if (message.type === 'system') {
      return (
        <div style={{ 
          color: '#1890ff', 
          fontSize: 13, 
          fontStyle: 'italic',
          display: 'flex',
          alignItems: 'center' 
        }}>
          <InfoCircleOutlined style={{ marginRight: 5 }} />
          {message.content}
        </div>
      );
    }

    // 非管理员看不到敏感内容
    if (message.hasSensitive && !isAdmin) {
      return (
        <div className="sensitive-content-placeholder">
          <Alert
            message="内容已隐藏"
            description="该内容含有敏感信息，已被系统自动隐藏"
            type="warning"
            showIcon
            style={{ padding: '8px 12px', fontSize: 12 }}
          />
        </div>
      );
    }
    
    // 管理员可以看到所有内容
    if (message.type === 'image') {
      return (
        <div>
          {message.media ? (
            <img 
              src={`data:${message.media.mimetype};base64,${message.media.data}`} 
              alt="图片" 
              style={{ maxWidth: '100%', borderRadius: 4 }} 
            />
          ) : (
            <div style={{ 
              background: '#f0f0f0', 
              height: 160, 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center', 
              borderRadius: 4 
            }}>
              <span style={{ color: '#999' }}>图片内容</span>
            </div>
          )}
          {message.hasSensitive && isAdmin && (
            <Tag color="warning" style={{ marginTop: 4 }}>含敏感内容</Tag>
          )}
        </div>
      );
    }
    
    if (message.type === 'file') {
      return (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <FileOutlined style={{ fontSize: 24, marginRight: 8 }} />
          {typeof message.content === 'string' ? message.content : JSON.stringify(message.content)}
          {message.hasSensitive && isAdmin && (
            <Tag color="warning" style={{ marginLeft: 4 }}>含敏感内容</Tag>
          )}
        </div>
      );
    }
    
    const content = typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
    
    return (
      <>
        {content}
        {message.hasSensitive && isAdmin && (
          <Tag color="warning" style={{ marginTop: 4, display: 'block' }}>含敏感内容</Tag>
        )}
      </>
    );
  };

  // 添加到CRM的处理函数
  const handleAddToCRM = () => {
    if (!activeContact) return;
    
    Modal.confirm({
      title: '添加到CRM',
      icon: <ExclamationCircleOutlined />,
      content: '确定要将该联系人添加到CRM系统吗？',
      onOk() {
        // 弹出表单
        let crmForm = {
          name: activeContact?.name || '',
          phone: activeContact?.phone || '',
          product: '',
          quantity: '',
          location: '',
          notes: ''
        };
        
        Modal.info({
          title: 'CRM信息',
          width: 500,
          content: (
            <Form layout="vertical" initialValues={crmForm}>
              <Form.Item label="客户名称" name="name">
                <Input onChange={(e) => crmForm.name = e.target.value} defaultValue={crmForm.name} />
              </Form.Item>
              <Form.Item label="联系电话" name="phone">
                <Input onChange={(e) => crmForm.phone = e.target.value} defaultValue={crmForm.phone} disabled={!isAdmin} />
              </Form.Item>
              <Form.Item label="产品" name="product">
                <Input onChange={(e) => crmForm.product = e.target.value} placeholder="请输入关注的产品" />
              </Form.Item>
              <Form.Item label="数量" name="quantity">
                <Input onChange={(e) => crmForm.quantity = e.target.value} placeholder="请输入数量" />
              </Form.Item>
              <Form.Item label="地区" name="location">
                <Input onChange={(e) => crmForm.location = e.target.value} placeholder="请输入地区" />
              </Form.Item>
              <Form.Item label="备注" name="notes">
                <TextArea rows={3} onChange={(e) => crmForm.notes = e.target.value} placeholder="请输入备注信息" />
              </Form.Item>
            </Form>
          ),
          okText: '保存',
          onOk() {
            // 调用API添加到CRM
            Promise.resolve().then(async () => {
              try {
                // 使用CRM服务添加联系人
                const result = await crmService.addContact({
                  ...crmForm,
                  contactId: activeContact.id, // 关联WhatsApp联系人ID
                  whatsappId: activeContact.phone // 使用电话号码作为WhatsApp ID
                });
                
                console.log('添加到CRM成功:', result);
                
                // 构建CRM信息显示文本
                const crmInfoText = `${crmForm.name} ${crmForm.quantity || ''} ${crmForm.product || ''} ${crmForm.location || ''}`.trim();
                
                // 更新联系人信息显示CRM标签
                setContacts(prev => prev.map(c => 
                  c.id === activeContact.id 
                    ? { 
                        ...c, 
                        inCRM: true,
                        crmInfo: crmInfoText,
                        crmId: result.id // 存储CRM ID用于后续更新
                      } 
                    : c
                ));
                
                // 更新当前活跃联系人
                setActiveContact(prev => prev ? { 
                  ...prev, 
                  inCRM: true,
                  crmInfo: crmInfoText,
                  crmId: result.id
                } : null);
                
                // 通知用户成功
                message.success('成功添加到CRM系统！');
                
                // 可选：发送系统消息到聊天
                const systemMessage = {
                  id: `system_${Date.now()}`,
                  content: `该联系人已添加到CRM系统 (产品: ${crmForm.product || '未指定'}, 数量: ${crmForm.quantity || '未指定'})`,
                  timestamp: new Date().toISOString(),
                  direction: 'system',
                  type: 'system',
                  sender: { id: 'system', name: '系统' }
                };
                
                setMessages(prev => [...prev, systemMessage]);
                
              } catch (error) {
                console.error('添加到CRM失败:', error);
                message.error('添加到CRM失败，请重试');
              }
            });
          }
        });
      }
    });
  };

  // 联系人菜单项
  const contactMenuItems = [
    {
      key: 'crm',
      label: '添加到CRM',
      onClick: handleAddToCRM
    },
    {
      key: 'block',
      label: '屏蔽联系人',
      danger: true
    }
  ];

  // 正在输入指示器组件
  const TypingIndicator = () => (
    <div className="typing-indicator">
      <div className="typing-dot"></div>
      <div className="typing-dot"></div>
      <div className="typing-dot"></div>
    </div>
  );

  // 添加手机号掩码函数
  const maskPhoneNumber = (phone, isAdmin) => {
    if (!phone) return '';
    if (isAdmin) return phone; // 管理员可以看到完整手机号
    
    // 移除所有非数字字符
    const digits = phone.replace(/\D/g, '');
    if (digits.length <= 4) return phone; // 太短的号码不处理
    
    // 保留前3位和后2位，中间用星号替代
    const maskedMiddle = '*'.repeat(Math.min(digits.length - 5, 6));
    return `${digits.substring(0, 3)}${maskedMiddle}${digits.substring(digits.length - 2)}`;
  };

  // 添加检测敏感内容的函数
  const isSensitiveContent = (message) => {
    if (!message || !message.content) return false;
    
    // 判断是否为图片类型
    if (message.type === 'image') {
      return true; // 所有图片都视为敏感内容
    }
    
    // 检查是否含有6位以上数字
    if (typeof message.content === 'string') {
      // 使用正则表达式匹配6位以上连续数字
      const longNumberRegex = /\d{6,}/;
      return longNumberRegex.test(message.content.replace(/\s+/g, ''));
    }
    
    return false;
  };

  // 使用React.memo优化联系人列表项
  const ContactItem = React.memo(({ 
    contact, 
    activeContactId, 
    onContactSelect, 
    isAdmin 
  }) => {
    return (
      <List.Item
        onClick={() => onContactSelect(contact)}
        className={`contact-item ${activeContactId === contact.id ? 'active' : ''}`}
        style={{ 
          cursor: 'pointer',
          background: activeContactId === contact.id ? '#f0f8ff' : 'transparent',
          padding: '8px 12px',
          borderBottom: '1px solid #f5f5f5',
          transition: 'background-color 0.3s',
          ...(contact.hasSensitive && isAdmin ? { background: '#fff7e6' } : {})
        }}
      >
        <List.Item.Meta
          avatar={
            <Badge count={contact.unreadCount > 0 ? contact.unreadCount : 0} size="small">
              <Avatar 
                className="contact-avatar"
                icon={<UserOutlined />} 
                style={{
                  backgroundColor: activeContactId === contact.id ? '#1890ff' : '#d9d9d9'
                }}
                size="small"
              >
                {contact.name?.[0]?.toUpperCase()}
                {activeContactId === contact.id && (
                  <span className="contact-status" />
                )}
              </Avatar>
            </Badge>
          }
          title={
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ 
                fontWeight: contact.unreadCount > 0 ? 'bold' : 'normal',
                color: contact.unreadCount > 0 ? '#1890ff' : 'inherit',
                fontSize: 14
              }}>
                {contact.name}
                {contact.inCRM && <Tag color="blue" style={{ marginLeft: 4, fontSize: 10, padding: '0 4px', height: 16, lineHeight: '16px' }}>CRM</Tag>}
              </span>
              <Text type="secondary" style={{ fontSize: 11 }}>
                {moment(contact.lastMessageTime).calendar()}
              </Text>
            </div>
          }
          description={
            <div>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {contact.hasSensitive && isAdmin && (
                  <Tag color="warning" style={{ marginRight: 4, fontSize: 10, lineHeight: '16px', padding: '0 4px', height: 16 }}>敏感</Tag>
                )}
                <Text ellipsis style={{ 
                  maxWidth: 180, 
                  color: contact.unreadCount > 0 ? '#262626' : '#8c8c8c',
                  fontWeight: contact.unreadCount > 0 ? 'bold' : 'normal',
                  fontSize: 12
                }}>
                  {typeof contact.lastMessage === 'string' 
                    ? contact.lastMessage 
                    : (contact.lastMessage && typeof contact.lastMessage.message === 'string' 
                      ? contact.lastMessage.message 
                      : '新消息')}
                </Text>
              </div>
              <div style={{ fontSize: 11, color: '#bfbfbf', marginTop: 2 }}>
                {contact.inCRM ? contact.crmInfo : (isAdmin ? contact.phone : maskPhoneNumber(contact.phone, isAdmin))}
              </div>
            </div>
          }
        />
      </List.Item>
    );
  });

  // 使用React.memo优化消息项
  const MessageItem = React.memo(({ 
    message, 
    renderMessageContent,
    isAdmin
  }) => {
    // 明确确定消息方向
    const isOutbound = message.direction === 'outbound' || 
                       message.fromMe === true || 
                       message.sender?.id === 'me';
    const isSystem = message.type === 'system' || message.direction === 'system';
    
    return (
      <List.Item
        style={{
          display: 'flex',
          justifyContent: isSystem ? 'center' : (isOutbound ? 'flex-end' : 'flex-start'),
          padding: '3px 0',
          border: 'none'
        }}
      >
        {/* 左侧头像 - 仅对方消息显示，系统消息不显示 */}
        {!isOutbound && !isSystem && (
          <Avatar 
            icon={<UserOutlined />} 
            style={{ 
              marginRight: 6, 
              backgroundColor: '#1890ff',
              alignSelf: 'flex-end',
              marginBottom: 4
            }}
            size={28}
          />
        )}
        
        {/* 消息气泡 */}
        <div
          className={`message ${isSystem ? 'message-system' : `message-${isOutbound ? 'outbound' : 'inbound'}`} ${message.hasSensitive ? 'message-sensitive' : ''}`}
        >
          {/* 发送者名称 - 系统消息不显示 */}
          {!isOutbound && !isSystem && (
            <div style={{ 
              fontSize: 11, 
              color: '#1890ff', 
              marginBottom: 3, 
              fontWeight: 'bold' 
            }}>
              {message.sender.name}
            </div>
          )}
          
          {/* 消息内容 */}
          <div style={{ wordBreak: 'break-word', fontSize: 14 }}>
            {renderMessageContent(message)}
          </div>
          
          {/* 时间和状态 - 系统消息简化显示 */}
          {!isSystem ? (
            <div className="message-time">
              {moment(message.timestamp).format('HH:mm')}
              {message.failed && (
                <Tag color="error" size="small" style={{ marginLeft: 4, padding: '0 4px', height: 16, lineHeight: '16px', fontSize: 10 }}>
                  发送失败
                </Tag>
              )}
            </div>
          ) : (
            <div style={{ fontSize: 10, color: '#8c8c8c', marginTop: 2, textAlign: 'center' }}>
              {moment(message.timestamp).format('HH:mm')}
            </div>
          )}
        </div>
        
        {/* 右侧头像 - 仅自己消息显示，系统消息不显示 */}
        {isOutbound && !isSystem && (
          <Avatar 
            style={{ 
              marginLeft: 6, 
              backgroundColor: '#87d068',
              alignSelf: 'flex-end',
              marginBottom: 4
            }}
            size={28}
          >我</Avatar>
        )}
      </List.Item>
    );
  });

  // 优化获取可见消息的函数
  const getVisibleMessages = (allMessages) => {
    // 如果消息少于100条，直接返回全部
    if (allMessages.length < 100) return allMessages;
    
    // 否则只返回最新的100条消息
    return allMessages.slice(-100);
  };
  
  // 优化消息渲染函数
  const renderMessages = () => {
    if (messages.length === 0) {
      if (loadingMessages) return <Spin />;
      
      return (
        <div style={{ 
          textAlign: 'center', 
          padding: '30px 0', 
          color: '#8c8c8c',
          background: '#f9f9f9',
          borderRadius: 8,
          margin: '20px 0'
        }}>
          <MessageOutlined style={{ fontSize: 36, color: '#d9d9d9', marginBottom: 12 }} />
          <div>暂无消息记录，开始发送消息吧！</div>
        </div>
      );
    }
    
    // 只渲染可见区域的消息
    const visibleMessages = getVisibleMessages(messages);
    
    return (
      <List
        dataSource={visibleMessages}
        renderItem={message => (
          <MessageItem 
            key={message.id}
            message={message}
            renderMessageContent={renderMessageContent}
            isAdmin={isAdmin}
          />
        )}
      />
    );
  };

  // 优化联系人选择处理函数
  const handleContactSelect = useCallback((contact) => {
    setActiveContact(contact);
    navigate(`/chat/${contact.id}`);
    loadMessages(contact.id);
  }, [navigate]);
  
  // 使用useMemo优化过滤后的联系人列表
  const filteredContacts = useMemo(() => {
    if (!searchInput) return contacts;
    
    return contacts.filter(contact => 
      contact.name?.toLowerCase().includes(searchInput.toLowerCase()) ||
      (contact.phone && contact.phone.includes(searchInput))
    );
  }, [contacts, searchInput]);

  // 在页面加载和卸载时添加性能监控
  useEffect(() => {
    console.time('ChatPage-Render');
    
    return () => {
      console.timeEnd('ChatPage-Render');
    };
  }, []);

  return (
    <Layout className="chat-container" style={{ height: 'calc(100vh - 112px)', background: '#fff' }}>
      {/* 联系人列表侧边栏 */}
      <Sider width={280} className="contact-list" style={{ background: '#fff', borderRight: '1px solid #f0f0f0', overflowY: 'auto' }}>
        <div style={{ 
          padding: '12px 12px 10px', 
          borderBottom: '1px solid #f5f5f5', 
          background: '#fafafa'
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <Title level={4} style={{ margin: 0, fontSize: 16 }}>聊天</Title>
            <Space>
              <Button type="text" icon={<PlusOutlined />} shape="circle" size="small" />
              <Button type="text" icon={<UserOutlined />} shape="circle" size="small" />
            </Space>
          </div>
          <Input.Search 
            placeholder="搜索联系人" 
            style={{ 
              borderRadius: 20,
              marginBottom: 4
            }}
            size="middle"
            onChange={(e) => setSearchInput(e.target.value)}
          />
        </div>
        
        <Spin spinning={loading}>
          <List
            dataSource={filteredContacts}
            renderItem={(contact) => (
              <ContactItem 
                key={contact.id}
                contact={contact}
                activeContactId={activeContact?.id}
                onContactSelect={handleContactSelect}
                isAdmin={isAdmin}
              />
            )}
          />
        </Spin>
      </Sider>
      
      {/* 聊天内容区域 */}
      <Content style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        {activeContact ? (
          <>
            {/* 聊天头部 */}
            <div className="chat-header"
              style={{ 
                padding: '8px 16px', 
                borderBottom: '1px solid #f0f0f0',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                background: '#fff',
                boxShadow: '0 1px 3px rgba(0,0,0,0.05)'
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar 
                  className="contact-avatar"
                  size={38} 
                  icon={<UserOutlined />} 
                  style={{ 
                    marginRight: 10,
                    backgroundColor: '#1890ff',
                    position: 'relative'
                  }}
                >
                  {activeContact.name?.[0]?.toUpperCase() || <UserOutlined />}
                  <span className="contact-status" style={{
                    position: 'absolute',
                    width: 10,
                    height: 10,
                    backgroundColor: '#52c41a',
                    borderRadius: '50%',
                    border: '2px solid #fff',
                    bottom: 0,
                    right: 0
                  }} />
                </Avatar>
                <div>
                  <Title level={4} style={{ margin: 0, fontSize: 16 }}>{activeContact.name}</Title>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <span style={{
                      width: 6,
                      height: 6,
                      backgroundColor: '#52c41a',
                      borderRadius: '50%',
                      marginRight: 4,
                      display: 'inline-block'
                    }}></span>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {isAdmin ? activeContact.phone : maskPhoneNumber(activeContact.phone, isAdmin)}
                    </Text>
                  </div>
                </div>
              </div>
              <div>
                <Space>
                  <Button 
                    type="text" 
                    icon={<MessageOutlined />} 
                    style={{ borderRadius: 20 }}
                    size="small"
                  />
                  <Dropdown 
                    menu={{ items: contactMenuItems }} 
                    trigger={['click']}
                    placement="bottomRight"
                  >
                    <Button 
                      type="text" 
                      icon={<MoreOutlined />} 
                      style={{ borderRadius: 20 }}
                      size="small"
                    />
                  </Dropdown>
                </Space>
              </div>
            </div>
            
            {/* 消息列表 */}
            <div className="messages-container">
              {/* 加载更多按钮 */}
              {hasMoreMessages && (
                <div className="load-more">
                  <Button 
                    type="link" 
                    loading={loadingMoreMessages}
                    onClick={loadMoreMessages}
                    size="small"
                  >
                    加载更多历史消息
                  </Button>
                </div>
              )}
              
              <Spin spinning={loadingMessages}>
                {renderMessages()}

                {/* 显示正在输入状态 */}
                {typing && (
                  <div style={{ display: 'flex', alignItems: 'center', margin: '4px 0' }}>
                    <Avatar 
                      icon={<UserOutlined />} 
                      style={{ 
                        marginRight: 6, 
                        backgroundColor: '#1890ff',
                        marginLeft: 5
                      }}
                      size={24}
                    />
                    <TypingIndicator />
                  </div>
                )}
                
                <div ref={messagesEndRef} />
              </Spin>
            </div>
            
            {/* 消息输入区域 */}
            <div className="input-container">
              <div style={{ 
                display: 'flex', 
                marginBottom: 6,
                justifyContent: 'space-between'
              }}>
                <Space>
                  {/* 预设文件下拉菜单 */}
                  <Dropdown
                    open={presetMenuVisible}
                    onOpenChange={setPresetMenuVisible}
                    menu={{
                      items: presetFiles.map(file => ({
                        key: file.id,
                        label: (
                          <div style={{ display: 'flex', alignItems: 'center' }}>
                            {file.type === 'pdf' && <FileOutlined style={{ marginRight: 8, color: '#f5222d' }} />}
                            {file.type === 'excel' && <FileOutlined style={{ marginRight: 8, color: '#52c41a' }} />}
                            {file.type === 'ppt' && <FileOutlined style={{ marginRight: 8, color: '#fa8c16' }} />}
                            {file.type === 'doc' && <FileOutlined style={{ marginRight: 8, color: '#1890ff' }} />}
                            {!['pdf', 'excel', 'ppt', 'doc'].includes(file.type) && <FileOutlined style={{ marginRight: 8 }} />}
                            <span>{`${file.name}.${file.type}`}</span>
                          </div>
                        ),
                        onClick: () => handleSendPresetFile(file.id)
                      }))
                    }}
                    trigger={['click']}
                  >
                    <Button 
                      type="text" 
                      icon={<PaperClipOutlined />}
                      style={{ borderRadius: 20 }}
                      size="small"
                    >
                      预设文件
                    </Button>
                  </Dropdown>
                  
                  {/* 文件上传按钮 */}
                  <Upload
                    beforeUpload={handleFileUpload}
                    showUploadList={false}
                    multiple={false}
                  >
                    <Button 
                      loading={uploadLoading} 
                      icon={<PlusOutlined />}
                      type="text"
                      style={{ borderRadius: 20 }}
                      size="small"
                    >
                      上传文件
                    </Button>
                  </Upload>
                </Space>
                
                {/* 显示活跃时间 */}
                {!isAdmin && (
                  <div style={{ fontSize: 11, color: '#8c8c8c' }}>
                    今日活跃: {Math.floor(activeTime / 60)}分{activeTime % 60}秒
                  </div>
                )}
              </div>
              
              {/* 消息输入框 */}
              <div className="message-input">
                <TextArea
                  value={messageInput}
                  onChange={e => setMessageInput(e.target.value)}
                  placeholder="输入消息..."
                  autoSize={{ minRows: 1, maxRows: 4 }}
                  onPressEnter={e => {
                    if (!e.shiftKey) {
                      e.preventDefault();
                      handleSendMessage();
                    }
                  }}
                  style={{ 
                    flex: 1, 
                    marginRight: 8,
                  }}
                  bordered={false}
                />
                <Button
                  type="primary"
                  icon={<SendOutlined />}
                  onClick={handleSendMessage}
                  disabled={!messageInput.trim()}
                  shape="circle"
                  size="middle"
                />
              </div>
              <div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 2, textAlign: 'center' }}>
                按 Enter 发送消息，按 Shift + Enter 换行
              </div>
            </div>
          </>
        ) : (
          <div className="empty-chat" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', background: '#f5f7f9' }}>
            <Card className="empty-chat-card" style={{ width: 340, textAlign: 'center', borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
              <MessageOutlined style={{ fontSize: 42, color: '#1890ff', marginBottom: 12 }} />
              <Title level={4} style={{ fontSize: 16 }}>选择一个联系人开始聊天</Title>
              <Paragraph type="secondary" style={{ fontSize: 13 }}>
                从左侧列表中选择一个联系人，开始聊天。
              </Paragraph>
            </Card>
          </div>
        )}
      </Content>
    </Layout>
  );
};

// 使用React.memo优化组件
export default React.memo(ChatPage); 